import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const blackList = ['/cms','/center','/message/all','/addArticle'] // 未登录，禁止访问，路由黑名单

router.beforeEach(async(to, from, next) => {
  // 进度条
  NProgress.start()
  // 动态设置title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const user = getToken()
  if (user) {
    //  如果输入后台路由
    if (to.path.indexOf('/cms') >= 0) {
      if (user.identity !== 'admin') {
        //  非管理员用户跳转首页
        next('/')
        return NProgress.done()
      }
    }
    if (to.path === '/login') {
      // 如果是管理员用户，跳转后台
      if (user.identity === 'admin') next({ path: '/cms' })
      //  配普通用户跳转首页
      else next('/')
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          next()
        } catch (error) {
          // 重置token
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 没有token
    if (blackList.indexOf(to.path) !== -1) {
      // 在黑名单里，需要登录
      Message.warning('请先登录')
      // next(`/login?redirect=${to.path}`)
      NProgress.done()
    } else {
      // 不在黑名单里，放行
      next()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
